package com.shareyi.netty.time;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.ByteBuffer;

public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        try {
            StringBuilder echoMsg = new StringBuilder();
            while (in.isReadable()) {
                char readByte = (char) in.readByte();
                System.out.print(readByte);
                System.out.flush();
                echoMsg.append(readByte);
            }
            ByteBuffer allocate = ByteBuffer.wrap(echoMsg.toString().getBytes());
            ctx.write(allocate);
        } finally {
            //新版本不需要这句
            ctx.flush();
            ctx.close();
            //ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
